import * as financeRecordService from '../services/financeRecord';
import * as indexPageService from '../services/indexPage';

export default {
  namespace: 'financeRecord',
  state: {
    totalCount: 0,
  	list: [],
    balance: null
  },
  reducers: {
    save(state, { payload: { list, totalCount} }) {
    	return { ...state, list, totalCount };
    },
    setBalance(state, { payload }) {
      return {
        ...state,
        balance: payload
      }
    }
  },
  effects: {
    *fetchBalance({ payload }, { call, put }) {
      const { data } = yield call(indexPageService.fetchBalance);
      if (data.success && data.data) {
        const result = data.data;
        yield put({
          type: 'setBalance',
          payload: {
            ...result
          },
        });
      }
    },
    *fetch({ payload }, { call, put }) {
    	const { data } = yield call(financeRecordService.fetch, { payload });
    	if (data) {
        const result = data.data;
    		yield put({
	    		type: 'save',
	    		payload: {
	    			list: result.list,
            totalCount: result.totalCount
	    		}
	    	});
    	}
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/page/financeRecord') {
          dispatch({ type: 'fetchBalance' })
        }
      });
    }
  }
};
